import { useEffect } from 'react';
import { useSnippetsStore } from '@renderer/stores';
import { useSelect } from '../useSelect';

export function useKeydown () {
  const snippets = useSnippetsStore(state => state.snippets)
  const activeId = useSnippetsStore(s => s.activeId)
  const setActiveId = useSnippetsStore(s => s.setActiveId)
  const { selectItem } = useSelect()

  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.code === 'Escape') {
        return window.api.closeWindow('search')
      } else if (e.code === 'Enter') {
        return selectItem(activeId)
      }

      if (!snippets.length) return

      const maxIndex = snippets.length - 1

      if (e.code === 'ArrowDown') {
        setActiveId(prevId => {
          const index = snippets.findIndex(i => i.id === prevId)
          if (index < maxIndex) {
            return snippets[index + 1].id
          }
          return snippets[0].id
        })
      } else if (e.code === 'ArrowUp') {
        setActiveId(prevId => {
          const index = snippets.findIndex(i => i.id === prevId)
          if (index > 0) {
            return snippets[index - 1].id
          }
          return snippets[maxIndex].id
        })
      }
    }

    document.body.addEventListener('keydown', handler)
    return () => {
      document.body.removeEventListener('keydown', handler)
    }
  }, [activeId, snippets])

  useEffect(() => {
    if (!snippets.length) return

    setActiveId(snippets[0].id)
  }, [snippets])
}
